package com.tlgen.orm.components.serializer;

import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

public class JsonResponseProcessor {

    private static final Set<String> EXCLUDED_FIELDS = new HashSet<>(Arrays.asList(
            "password", "secretKey"
    ));

    // 获取系统配置的ObjectMapper
    private static ObjectMapper getConfiguredObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return mapper;
    }

    /**
     * 安全处理响应数据（敏感字段过滤 + Long转String）
     */
    @SuppressWarnings("unchecked")
    public static <T> T processResponse(T data) {
        if (data == null) return null;

        ObjectMapper mapper = getConfiguredObjectMapper();

        try {
            // 1. 注册动态过滤器（排除敏感字段）
            SimpleBeanPropertyFilter filter = new SimpleBeanPropertyFilter() {
                @Override
                protected boolean include(BeanPropertyWriter writer) {
                    return !EXCLUDED_FIELDS.contains(writer.getName().toLowerCase());
                }

                @Override
                protected boolean include(PropertyWriter writer) {
                    return !EXCLUDED_FIELDS.contains(writer.getName().toLowerCase());
                }
            };

            SimpleFilterProvider filterProvider = new SimpleFilterProvider()
                    .addFilter("responseFilter", filter)
                    .setFailOnUnknownId(false);

            mapper.addMixIn(Object.class, DynamicFilterMixIn.class);
            mapper.setFilterProvider(filterProvider);

            // 2. 添加Long转String序列化器
            SimpleModule longToStringModule = new SimpleModule();
            longToStringModule.addSerializer(Long.class, new LongToStringSerializer());
            longToStringModule.addSerializer(long.class, new LongToStringSerializer());
            mapper.registerModule(longToStringModule);

            // 3. 序列化+反序列化处理
            String json = mapper.writeValueAsString(data);
            return (T) mapper.readValue(json, data.getClass());
        } catch (JsonProcessingException e) {
            // 序列化错误处理（进行字段级过滤）
            return primitiveFieldFilter(data);
        } catch (IOException e) {
            // 反序列化错误处理（返回原始数据）
            System.err.println("安全处理失败: " + e.getMessage());
            return data;
        }
    }

    // 基础字段过滤（当高级处理失败时使用）
    private static <T> T primitiveFieldFilter(T obj) {
        if (obj == null) return null;

        try {
            // 通过反射移除敏感字段
            Class<?> clazz = obj.getClass();
            for (String fieldName : EXCLUDED_FIELDS) {
                try {
                    java.lang.reflect.Field field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);
                    field.set(obj, null);
                } catch (NoSuchFieldException e) {
                    // 忽略不存在的字段
                } catch (IllegalAccessException e) {
                    // 访问权限问题处理
                }
            }
            return obj;
        } catch (Exception e) {
            return obj; // 最低保障返回原始数据
        }
    }

    @JsonFilter("responseFilter")
    private static abstract class DynamicFilterMixIn {}

}